// miniprogram/pages/location/location.js
import data from './data'

var bmap = require('../../libs/bmap-wx.js');
var app = getApp()

var BMap
var wxMarkerData = [];

Page({

  /**
   * 页面的初始数据
   */
  data: {
    sugData: [],
    city: '北京市',
    cityValue: '110000',
    options1: data,
    value1: [],
    scrollTop: 0, //吸顶插件
    statusSearch: 'hiddenSearch',
    viewName: '搜索地址',
    locationName: '未获取到当前位置',
    cityTemp: '',
    locationNameTemp: '',
    addressTemp: '',
    longitudeTemp: '',
    latitudeTemp: ''
  },

  //吸顶插件
  onPageScroll(e) {
    console.log('onPageScroll', e.scrollTop)
    this.setData({
      scrollTop: e.scrollTop,
    })
  },

  selectCity: function () {
    this.setData({
      visible1: true
    })
  },

  onClose1() {
    this.setData({
      visible1: false
    })
  },

  onChange1(e) {
    if ((e.detail.options[e.detail.options.length - 1].value) % 1000 != 0) {
      this.setData({
        city: e.detail.options[e.detail.options.length - 1].label,
        cityValue: e.detail.options[e.detail.options.length - 1].value
      })
    }
    // console.log('onChange1', e.detail)
    // console.log('onChange1', e.detail.options[e.detail.options.length - 1].label)
    // console.log('onChange1', e.detail.options[e.detail.options.length - 1].value)
  },

  selectLocation: function (e) {
    // console.log(e)
    // console.log(e.currentTarget.dataset.address)
    // console.log(e.currentTarget.dataset.lng)
    // console.log(e.currentTarget.dataset.lat)

    app.globalData.city = e.currentTarget.dataset.city; //城市名,市或区县
    app.globalData.locationName = e.currentTarget.dataset.name //地点名
    app.globalData.address = e.currentTarget.dataset.address //地址信息
    app.globalData.longitude = e.currentTarget.dataset.lng; //经度
    app.globalData.latitude = e.currentTarget.dataset.lat; //维度

    wx.navigateBack()
  },

  getMapClass: function () {
    if (BMap == null) {
      BMap = new bmap.BMapWX({
        ak: app.globalData.baiduAK
      });
    }
  },

  // 绑定input输入 
  bindKeyInput: function (e) {
    var that = this;
    // 新建百度地图对象 
    that.getMapClass()
    var fail = function (data) {
      console.log(data)
    };
    var success = function (data) {
      that.setData({
        viewName: '搜索地址',
        statusSearch: 'showSearch',
        sugData: data.result
      });
      // console.log(that.data)
      // console.log(that.data.sugData)
    }
    // 发起suggestion检索请求 
    BMap.suggestion({
      query: e.detail.value,
      region: that.data.city,
      city_limit: true,
      fail: fail,
      success: success
    })
  },

  getLocationAuth: function () {
    var that = this;
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          //未授权
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                //取消授权
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
              } else if (res.confirm) {
                //确定授权，通过wx.openSetting发起授权请求
                wx.openSetting({
                  success: function (res) {
                    if (res.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权，调用wx.getLocation的API
                      that.getUserLocation();
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          //用户首次进入页面,调用wx.getLocation的API
          that.getUserLocation();
        } else {
          // console.log('授权成功')
          //调用wx.getLocation的API
          that.getUserLocation();
        }
      }
    })
  },

  getUserLocation: function () {
    var that = this
    // 新建百度地图对象 
    that.getMapClass()
    var fail = function (data) {
      // console.log(data)
      that.setData({
        locationName: '未获取到当前位置'
      });
    };
    var success = function (data) {
      // console.log(data)
      wxMarkerData = data.wxMarkerData;

      that.setData({
        locationName: data.originalData.result.pois[0].name
      })

      that.setData({
        cityTemp: data.originalData.result.addressComponent.city,
        locationNameTemp: data.originalData.result.pois[0].name,
        lonaddressgitudeTemp: wxMarkerData[0].address,
        longitudeTemp: wxMarkerData[0].longitude,
        latitudeTemp: wxMarkerData[0].latitude
      });

      // console.log(app.globalData)
    }
    // 发起regeocoding检索请求 
    BMap.regeocoding({
      fail: fail,
      success: success,
      iconPath: '../../images/map/marker_red.png',
      iconTapPath: '../../images/map/marker_red.png'
    });

  },

  selectReLocation: function () {
    var that = this
    if (that.data.locationName != null && that.data.locationName != '') {
      app.globalData.city = that.data.cityTemp
      app.globalData.locationName = that.data.locationNameTemp
      app.globalData.address = that.data.addressTemp
      app.globalData.longitude = that.data.longitudeTemp
      app.globalData.latitude = that.data.latitudeTemp

      wx.navigateBack()
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    if (app.globalData.city != '') {
      that.setData({
        city: app.globalData.city
      })
    }

    // console.log(app.globalData)
    if (app.globalData.locationName != '') {

      that.setData({
        locationName: app.globalData.locationName
      })

      that.getMapClass()
      // 发起suggestion检索请求 
      BMap.suggestion({
        query: app.globalData.address == null || app.globalData.address == '' ? app.globalData.locationName : app.globalData.address,
        region: app.globalData.city,
        city_limit: true,
        fail: function (data) {
          console.log(data)
        },
        success: function (data) {
          that.setData({
            viewName: '搜索地址',
            statusSearch: 'showSearch',
            sugData: data.result
          })
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})